package com.heima.account.handler;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.heima.commons.enums.BusinessErrors;
import com.heima.commons.exception.BusinessRuntimeException;
import com.heima.modules.po.VehiclePO;
import okhttp3.*;
import org.apache.commons.io.FileUtils;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Base64;

@Component
public class AiHelper {
    @Value("${baidu.apikey}")
    private String API_KEY;
    @Value("${baidu.secretkey}")
    private String SECRET_KEY;

    private final static Logger logger = LoggerFactory.getLogger(AiHelper.class);

    final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();


    public static void main(String []args) throws IOException {
        String code = new AiHelper().getLicense(null);
        System.out.println(code);
    }

    /*

    图像识别，获取车牌信息
    文档（行驶证识别）：https://cloud.baidu.com/doc/OCR/s/yk3h7y3ks
    文档（车牌识别）：https://cloud.baidu.com/doc/OCR/s/ck3h7y191
    获取车辆照片url
    将url下载到某个临时文件夹
    将文件编码为base64
    调百度AI接口，返回对应信息
    对比：行驶证车牌 和 车辆车牌是否一致
    如果一致，设置车牌信息，认证通过，身份变更为车主

    简化版业务流程（至少完成）：识别车辆车牌号即可

    * */
    public String getLicense(VehiclePO vehiclePO) throws IOException {
//        // 下载图片到临时文件夹
//        File tempFile = downloadImageToTempFile(vehiclePO.getCarFrontPhoto());
//
//        // 将临时文件转换为Base64编码
//        String fileContentAsBase64 = getFileContentAsBase64(tempFile.getAbsolutePath(), true);
//
//        // 准备请求体
//        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
//        RequestBody body = RequestBody.create(mediaType, "image=" + fileContentAsBase64);
//
//        // 构建请求
//        Request request = new Request.Builder()
//                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + getAccessToken())
//                .method("POST", body)
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                .addHeader("Accept", "application/json")
//                .build();
//
//        // 发送请求
//        Response response = HTTP_CLIENT.newCall(request).execute();
//        String responseBody = response.body().string();
//        System.out.println(responseBody);
//
//        // 解析响应
//        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseBody);
//        String carNumber = jsonObject.getJSONObject("words_result").getString("number");
//
//        // 设置车牌信息
//        vehiclePO.setCarNumber(carNumber);
//
//        return carNumber;
//
//    }
//
//    private File downloadImageToTempFile(String carFrontPhoto) throws IOException{
//        URL url = new URL(carFrontPhoto);
//        InputStream in = url.openStream();
//        File tempFile = File.createTempFile("car_front_photo", ".jpg");
//        Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
//        in.close();
//        return tempFile;
//    }
//
//    /**
//     * 获取文件base64编码
//     *
//     * @param path      文件路径
//     * @param urlEncode 如果Content-Type是application/x-www-form-urlencoded时,传true
//     * @return base64编码信息，不带文件头
//     * @throws IOException IO异常
//     */
//    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
//        byte[] b = Files.readAllBytes(Paths.get(path));
//        String base64 = Base64.getEncoder().encodeToString(b);
//        if (urlEncode) {
//            base64 = URLEncoder.encode(base64, "utf-8");
//        }
//        return base64;
//    }
//
//    private String getAccessToken() throws IOException{
//        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
//        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
//                + "&client_secret=" + SECRET_KEY);
//        Request request = new Request.Builder()
//                .url("https://aip.baidubce.com/oauth/2.0/token")
//                .method("POST", body)
//                .addHeader("Content-Type", "application/x-www-form-urlencoded")
//                .build();
//        Response response = HTTP_CLIENT.newCall(request).execute();
//        return new JSONObject(response.body().string()).getString("access_token");
//    }
        // 下载车辆前部照片到临时文件夹
        File carFrontPhotoFile = downloadFile(vehiclePO.getCarFrontPhoto());
        // 将临时文件转换为Base64编码
        String carFrontPhotoBase64 = getFileContentAsBase64(carFrontPhotoFile.getAbsolutePath(), true);
        // 下载行驶证照片到临时文件夹
        File carBackPhotoFile = downloadFile(vehiclePO.getCarBackPhoto());
        // 将临时文件转换为Base64编码
        String carBackPhotoBase64 = getFileContentAsBase64(carBackPhotoFile.getAbsolutePath(), true);
        // 获取访问令牌
        String accessToken = getAccessToken();
        // 调用百度AI接口识别车辆车牌
        String carNumber = recognizeLicensePlate(carFrontPhotoBase64, accessToken);
        // 调用百度AI接口识别行驶证车牌
        String licenseNumber = recognizeDrivingLicense(carBackPhotoBase64, accessToken);
        // 对比车牌信息
        if (carNumber.equals(licenseNumber)) {
            // 设置车牌信息，认证通过，身份变更为车主
            vehiclePO.setCarNumber(carNumber);
            vehiclePO.setStatus(1); // 假设有一个方法来设置车主身份
            return carNumber;
        } else {
            throw new RuntimeException("车牌与行驶证号牌号码不一致!");
        }
    }
    private File downloadFile(String imageUrl) throws IOException {

        URL url = new URL(imageUrl);
        InputStream in = url.openStream();
        File tempFile = File.createTempFile("temp_image", ".jpg");
        Files.copy(in, tempFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
        in.close();
        return tempFile;
    }
    static String getFileContentAsBase64(String path, boolean urlEncode) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        String base64 = Base64.getEncoder().encodeToString(b);
        if (urlEncode) {
            base64 = URLEncoder.encode(base64, "utf-8");
        }
        return base64;
    }
    private String getAccessToken() throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "grant_type=client_credentials&client_id=" + API_KEY
                + "&client_secret=" + SECRET_KEY);
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        return new JSONObject(response.body().string()).getString("access_token");
    }

    private String recognizeLicensePlate(String imageBase64, String accessToken) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + imageBase64);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/license_plate?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();
        System.out.println(responseBody);

        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseBody);
        return jsonObject.getJSONObject("words_result").getString("number");
    }
    private String recognizeDrivingLicense(String imageBase64, String accessToken) throws IOException {
        MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded");
        RequestBody body = RequestBody.create(mediaType, "image=" + imageBase64);

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rest/2.0/ocr/v1/vehicle_license?access_token=" + accessToken)
                .method("POST", body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .addHeader("Accept", "application/json")
                .build();

        Response response = HTTP_CLIENT.newCall(request).execute();
        String responseBody = response.body().string();
        System.out.println(responseBody);

        com.alibaba.fastjson.JSONObject jsonObject = com.alibaba.fastjson.JSONObject.parseObject(responseBody);
        return jsonObject.getJSONObject("words_result").getJSONObject("号牌号码").getString("words");
    }
}

